package com.blockmeta.bbs.immodule.widget;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blockmeta.bbs.baselibrary.net.callback.BaseResponseCallBack;
import com.blockmeta.bbs.baselibrary.utils.DimentionsUtil;
import com.blockmeta.bbs.baselibrary.utils.LoadPicUtil;
import com.blockmeta.bbs.baselibrary.widget.popupview.BaseBottomPopupWindow;
import com.blockmeta.bbs.businesslibrary.net.pojo.BaseCodeResponse;
import com.blockmeta.bbs.businesslibrary.net.retrofit.RetrofitFactory;
import com.blockmeta.bbs.businesslibrary.net.rxjava.CommonSubscriber;
import com.blockmeta.bbs.businesslibrary.net.rxjava.RxUtil;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.businesslibrary.widget.CircleImageView;
import com.blockmeta.bbs.immodule.R;
import com.blockmeta.bbs.immodule.activity.HongbaoDetailActivity;
import com.blockmeta.bbs.immodule.bean.HongbaoDetail;
import com.blockmeta.bbs.immodule.bean.Params;
import com.blockmeta.bbs.immodule.corebean.Impl.IMApplicationContext;
import com.blockmeta.bbs.immodule.dao.ChatMessage;
import com.blockmeta.bbs.immodule.dao.IMUserEntity;
import com.blockmeta.bbs.immodule.net.api.QiangHongbaoApi;
import com.github.florent37.viewanimator.AnimationListener;
import com.github.florent37.viewanimator.ViewAnimator;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import java.util.ArrayList;
import java.util.List;

import static com.blankj.utilcode.util.ActivityUtils.startActivity;


public class Popup_Qiang_Hongbao extends BaseBottomPopupWindow implements View.OnClickListener {

    private RelativeLayout hongbaoWindow;
    private RelativeLayout outHongbao;
    private RelativeLayout topWhitehongbao;
    private RelativeLayout topHongbao;
    private ImageView coverHongbao;
    private ImageView ibtnQiang;
    private RelativeLayout rlayoutContent;
    private LinearLayout hongbaoFrom;
    private CircleImageView contactsAvatar;
    private TextView tvHongbaoFrom;
    private TextView tvHongbaoNothing;
    private TextView tvGongxi;
    private TextView tvHongbaoResult;
    private TextView tvHongbaoUnit;
    private TextView tvShoeHongbaoDetail;
    private ImageView ivSmallcoin;
    private TextView tvRemark;
    private ImageView ivHongbaoClose;
    private Button btnIknow;
    private HongbaoDetail mHongbaoDetail;
    private List<HongbaoDetail.CandyKidsListBean> candyKidsList;
    private long mChatGroupId = 0;



    public <T extends ChatMessage> Popup_Qiang_Hongbao(Context context, HongbaoDetail hongbaoDetail, T item) {
        super(context);
        mHongbaoDetail = hongbaoDetail;
        mChatGroupId = (item.getMsgType() == ChatMessage.MSG_TYPE_UCG ? item.getChatGroupId() : 0);
        judgeShowResult(mHongbaoDetail);
        bindUserInfo(item.getFromId());
    }

    private void bindUserInfo(long fromId) {
        IMApplicationContext.getUserDomainService().getUser(fromId, false, new BaseResponseCallBack<String, IMUserEntity>() {
            @Override
            public void fail(String msg) {
            }

            @Override
            public void success(IMUserEntity item) {
                LoadPicUtil.loadWithPicasso(contactsAvatar, item.getAvatarPath());
                String text = TextUtils.isEmpty(item.getRemarkName()) ? item.getName() : item.getRemarkName();
                text = text + "的红包";
                tvHongbaoFrom.setText(text);
            }
        });
    }


    @Override
    public int getResId() {
        return R.layout.hongbao_pop_layout2;
    }

    @Override
    protected void bindEvent() {

        hongbaoWindow = (RelativeLayout) findViewById(R.id.hongbao_window);
        outHongbao = (RelativeLayout) findViewById(R.id.out_hongbao);
        topWhitehongbao = (RelativeLayout) findViewById(R.id.top_whitehongbao);
        topHongbao = (RelativeLayout) findViewById(R.id.top_hongbao);
        coverHongbao = (ImageView) findViewById(R.id.cover_hongbao);
        ibtnQiang = (ImageView) findViewById(R.id.ibtn_qiang);
        rlayoutContent = (RelativeLayout) findViewById(R.id.rlayout_content);
        hongbaoFrom = (LinearLayout) findViewById(R.id.hongbao_from);
        contactsAvatar = (CircleImageView) findViewById(R.id.contacts_avatar);
        tvHongbaoFrom = (TextView) findViewById(R.id.tv_hongbao_from);
        tvHongbaoNothing = (TextView) findViewById(R.id.tv_hongbao_nothing);
        tvGongxi = (TextView) findViewById(R.id.tv_gongxi);
        tvHongbaoResult = (TextView) findViewById(R.id.tv_hongbao_result);
        tvHongbaoUnit = (TextView) findViewById(R.id.tv_hongbao_unit);
        tvShoeHongbaoDetail = (TextView) findViewById(R.id.tv_show_hongbao_detail);
        ivSmallcoin = (ImageView) findViewById(R.id.iv_smallcoin);
        tvRemark = (TextView) findViewById(R.id.tv_remark);
        ivHongbaoClose = (ImageView) findViewById(R.id.iv_hongbao_close);
        btnIknow = (Button) findViewById(R.id.btn_hongbao_iknow);

        ibtnQiang.setOnClickListener(this);
        btnIknow.setOnClickListener(this);
        tvShoeHongbaoDetail.setOnClickListener(this);

    }

    //判断能不能再抢，不能则显示结果
    private boolean judgeShowResult(HongbaoDetail detail) {
        if (detail.getStatus() == 0) {
            candyKidsList = detail.getCandyKidsList();
            if (candyKidsList != null && candyKidsList.size() > 0) {
                for (int i = 0; i < candyKidsList.size(); i++) {
                    HongbaoDetail.CandyKidsListBean bean = candyKidsList.get(i);
                    if (bean.getUserId() == AccountHelper.getUidInt()) {
                        //说明已经抢过了
                        showResult(bean.getCandyNum());

                        return true;
                    }
                    if (i == candyKidsList.size() - 1) {
                        //还可以抢
                        return false;
                    }
                }
            }else {
                //如果是空，说明还可以抢
                return false;
            }
        } else {
            candyKidsList = detail.getCandyKidsList();
            if (candyKidsList != null && candyKidsList.size() > 0) {
                for (int i = 0; i < candyKidsList.size(); i++) {
                    HongbaoDetail.CandyKidsListBean bean = candyKidsList.get(i);
                    if (bean.getUserId() == AccountHelper.getUidInt()) {
                        showResult(bean.getCandyNum());
                        return true;
                    }
                    if (i == candyKidsList.size() - 1) {
                        showResult(0);
                        return true;
                    }
                }
            }
        }
        return true;
    }


    private void showResult(int candyNum) {
        ibtnQiang.setVisibility(View.GONE);
        rlayoutContent.setVisibility(View.VISIBLE);
//        topHongbao.setPivotY(0);
//        topHongbao.setRotationX(-180);
        topHongbao.setVisibility(View.GONE);
        coverHongbao.setVisibility(View.VISIBLE);
        showCandyNum(candyNum);
    }

    private void showCandyNum(int candyNum) {
        btnIknow.setText("我知道了");
        tvShoeHongbaoDetail.setVisibility(View.VISIBLE);
        if (candyNum == 0) {
            tvHongbaoFrom.setTextColor(Color.parseColor("#FFA27600"));
            hongbaoFrom.setVisibility(View.VISIBLE);
            tvHongbaoNothing.setVisibility(View.VISIBLE);
            tvGongxi.setVisibility(View.GONE);
            tvHongbaoResult.setVisibility(View.GONE);
            tvHongbaoUnit.setVisibility(View.GONE);
        } else {
            hongbaoFrom.setVisibility(View.GONE);
            tvHongbaoResult.setText(candyNum + "");
        }
    }

    @Override
    public View getClickToDismissView() {
        return popupView.findViewById(R.id.iv_hongbao_close);
    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.ibtn_qiang) {
            qiangHongbao();


        }else if(v.getId() == R.id.btn_hongbao_iknow){
            if(ibtnQiang.getVisibility() == View.VISIBLE){
                qiangHongbao();
            }else {
                dismiss();
            }
        }else if(v.getId() == R.id.tv_show_hongbao_detail){
            Intent memberIntent = new Intent(getContext(), HongbaoDetailActivity.class);
            memberIntent.putExtra(Params.HONGBAODETAIL, mHongbaoDetail);
            memberIntent.putExtra(Params.CIRCLE_ID, mChatGroupId);
            getContext().startActivity(memberIntent);

        }
    }

    private void qiangHongbao() {
        //开启旋转
        ViewAnimator
                .animate(ibtnQiang)
                .rotationY(0, 90, 270, 360)
                .interpolator(new LinearInterpolator())
                .repeatCount(10)
                .duration(300)
                .start();

        RetrofitFactory.getRetrofit().create(QiangHongbaoApi.class)
                .getCandy(mHongbaoDetail.getId())
                .compose(RxUtil.<BaseCodeResponse<HongbaoDetail>>rxSchedulerHelper())
                .compose(RxUtil.<HongbaoDetail>commonResultByCode())
                .compose(((RxAppCompatActivity) getContext()).<HongbaoDetail>bindToLifecycle())
                .subscribe(new CommonSubscriber<HongbaoDetail>(getContext()) {
                    @Override
                    public void onNext(HongbaoDetail detail) {
                        ibtnQiang.setVisibility(View.GONE);
                        float contentHeight = DimentionsUtil.dp2px(170);
                        float contentWidth = DimentionsUtil.dp2px(250);
                        mHongbaoDetail = detail;
                        candyKidsList = detail.getCandyKidsList();
                        if (candyKidsList != null && candyKidsList.size() > 0) {
                            for (int i = 0; i < candyKidsList.size(); i++) {
                                HongbaoDetail.CandyKidsListBean bean = candyKidsList.get(i);
                                Log.i("author", "clickhongbao result" + bean.toString());
                                if (bean.getUserId() == AccountHelper.getUidInt()) {
                                    showCandyNum(bean.getCandyNum());
                                    break;
                                }
                                if (i == candyKidsList.size() - 1) {
                                    showCandyNum(0);
                                }
                            }
                        }else {
                            showCandyNum(0);
                        }

                        ViewAnimator
                                .animate(topHongbao)
                                .rotationX(0, -180)
                                .pivotY(0)
                                .interpolator(new DecelerateInterpolator())
                                .duration(500)
                                .onStop(new AnimationListener.Stop() {
                                    @Override
                                    public void onStop() {
                                        coverHongbao.setVisibility(View.VISIBLE);
                                        rlayoutContent.setVisibility(View.VISIBLE);
                                        ivSmallcoin.setVisibility(View.VISIBLE);
                                    }
                                })
                                .thenAnimate(rlayoutContent)
                                .translationY(100, 80, 30, 0)
//                                .pivotX(contentWidth / 2)
//                                .pivotY(contentHeight)
//                                .scaleY(0f, 0.5f, 1f)
//                                .scaleX(0.5f, 0.8f, 1f)
                                .duration(300)
                                .andAnimate(ivSmallcoin)
                                .scale(1f, 1.25f, 1.5f)
                                .duration(300)
                                .andAnimate(topHongbao)
                                .alpha(1f, 0.5f, 0f)
                                .onStop(new AnimationListener.Stop() {
                                    @Override
                                    public void onStop() {
                                        topHongbao.setVisibility(View.GONE);
                                    }
                                })
                                .start();
                    }
                });
    }


    public void showPop() {
        if (!isShowing()) {
            showPopupWindow();
        }
    }

    @Override
    public View initAnimaView() {
        return null;
    }
}
